﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Input;

namespace Resource.AttachedProperty
{
    public class ScrollerViewBehavior
    {
        public static bool GetScrollerWithMouseWheel(DependencyObject obj)
        {
            return (bool)obj.GetValue(ScrollerWithMouseWheelProperty);
        }

        public static void SetScrollerWithMouseWheel(DependencyObject obj, bool value)
        {
            obj.SetValue(ScrollerWithMouseWheelProperty, value);
        }

        public static readonly DependencyProperty ScrollerWithMouseWheelProperty =
            DependencyProperty.RegisterAttached("ScrollerWithMouseWheel", typeof(bool), typeof(ScrollerViewBehavior), new PropertyMetadata(OnScrollerWithMouseWheelChanged));

        private static void OnScrollerWithMouseWheelChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            ScrollViewer scrollerViewer = target as ScrollViewer;
            if ((bool)e.NewValue == true)
            {
                MouseWheelEventHandler mouseWheelEventHander = (sender, ea) => {
                    scrollerViewer.ScrollToVerticalOffset(scrollerViewer.VerticalOffset - ea.Delta / 2);
                    ea.Handled = true;
                };
                scrollerViewer.PreviewMouseWheel += mouseWheelEventHander;                
            }
        }
    }
}
